package com.jeegot.mall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeegot.common.exception.JeegotException;
import com.jeegot.mall.entity.Product;
import com.jeegot.mall.entity.ProductCategory;
import com.jeegot.mall.entity.ProductImage;
import com.jeegot.mall.entity.ProductSkuItem;
import com.jeegot.mall.mapper.ProductMapper;
import com.jeegot.mall.service.*;
import com.jeegot.mall.task.ProductViewCountUpdateTask;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author wjun_java@163.com
 * @since 2021-06-10
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

	@Autowired
	private IProductSkuItemService productSkuItemService;

	@Autowired
	private IProductImageService productImageService;

	@Autowired
	private IProductCommentService productCommentService;

	@Autowired
	private IProductCategoryService productCategoryService;

	@Override
	@Transactional
	public void saveProduct(Product product) throws Exception {

		List<ProductSkuItem> productSkuItemList = getProductSkuItem(product);
		if(!productSkuItemList.isEmpty()) {
			//如果有sku的情况下，使用第一个sku的价格跟库存
			ProductSkuItem productSkuItem = productSkuItemList.get(0);
			product.setPrice(productSkuItem.getPrice());
			product.setOriginPrice(productSkuItem.getOriginPrice());
			product.setStock(productSkuItem.getStock());
		}

		saveOrUpdate(product);

		//删除商品分类
		getBaseMapper().deleteRelationByProductId(product.getId());

		final Long[] productCategoryList = product.getProductCategory();
		if(productCategoryList != null && productCategoryList.length>0) {
			getBaseMapper().saveProductCategoryRelation(product.getId(), Arrays.asList(productCategoryList));
		}

		final String[] productTag = product.getProductTag();
		if(productTag != null && productTag.length>0) {
			//插入新的标签
			List<Long> tagList = new ArrayList<>();
			for (String tag : productTag) {
				if(StringUtils.isNotBlank(tag)) {
					ProductCategory articleCategory = findByTitle(tag);
					if(articleCategory == null) {
						articleCategory = new ProductCategory();
						articleCategory.setTitle(tag);
						articleCategory.setType(ProductCategory.TAG_TYPE);
						productCategoryService.save(articleCategory);
					}
					tagList.add(articleCategory.getId());
				}
			}
			getBaseMapper().saveProductCategoryRelation(product.getId(), tagList);
		}

		//商品轮播图处理
		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("product_id", product.getId());
		productImageService.remove(queryWrapper);
		if(product.getImageSrcs() != null) {
			List<ProductImage> productImages = new ArrayList<>();
			for (int i=0; i<product.getImageSrcs().length; i++) {
				ProductImage productImage = new ProductImage();
				productImage.setProductId(product.getId());
				productImage.setImagePath(product.getImageSrcs()[i]);
				productImage.setSortNum(i);
				productImages.add(productImage);
			}
			productImageService.saveBatch(productImages);
		}

		//移除旧的sku属性
		List<ProductSkuItem> oldProductSkuItemList = productSkuItemService.getProductSkuItemList(product.getId());
		for(ProductSkuItem productSkuItem : oldProductSkuItemList) {
			productSkuItemService.removeById(productSkuItem.getId());
		}
		if(!productSkuItemList.isEmpty()) {
			//插入新的sku属性
			productSkuItemService.saveBatch(productSkuItemList);
		}

	}

	ProductCategory findByTitle(String title) {
		QueryWrapper<ProductCategory> queryWrapper = new QueryWrapper();
		queryWrapper.eq("title", title.trim());
		queryWrapper.eq("type", ProductCategory.TAG_TYPE);
		return productCategoryService.getOne(queryWrapper);
	}

	List<ProductSkuItem> getProductSkuItem(Product product) {
		List<ProductSkuItem> addProductSkuItems = new ArrayList<>();
		String skuItems = product.getSkuItems();
		if(StringUtils.isNotBlank(skuItems)) {
			try {
				JSONArray skuJsonArr = JSONArray.parseArray(skuItems);
				if(skuJsonArr != null && skuJsonArr.size()>0) {
					for(int i=0; i<skuJsonArr.size();i++) {
						JSONObject jsonObj = skuJsonArr.getJSONObject(i);
						//Integer skuId = jsonObj.getInteger("id");
						String skuName = jsonObj.getString("skuName");
						String skuProperties = jsonObj.getString("skuProperties");
						String price = jsonObj.getString("price");
						String marketPrice = jsonObj.getString("marketPrice");
						String stock = jsonObj.getString("stock");

						if(StringUtils.isBlank(price) || StringUtils.isBlank(marketPrice) || StringUtils.isBlank(stock)) {
							throw new JeegotException("请填写完整规格" + skuName + "，价格跟库存信息");
						}

						ProductSkuItem productSkuItem = new ProductSkuItem();
						productSkuItem.setProductId(product.getId());
						productSkuItem.setSkuName(skuName);
						productSkuItem.setSkuProperties(skuProperties);
						productSkuItem.setOriginPrice(new BigDecimal(marketPrice));
						productSkuItem.setPrice(new BigDecimal(price));
						productSkuItem.setStock(Integer.valueOf(stock));
						addProductSkuItems.add(productSkuItem);
					}
				}
			} catch (Exception e) {
				throw new JeegotException(e.getMessage());
			}
		}
		return addProductSkuItems;
	}


	@Override
	public Page<ProductVo> pageProduct(Page pageParam, QueryWrapper queryWrapper) {
		return getBaseMapper().pageProduct(pageParam, queryWrapper);
	}

	@Override
	public ProductInfoVo getProductById(Long id) {
		ProductViewCountUpdateTask.recordCount(id);
		ProductInfoVo productInfo = getBaseMapper().getProductById(id);
		if(productInfo != null) {
			List<ProductImage> productImageList = productImageService.getProductImageList(id);
			productInfo.setImageSrcs(productImageList.stream().map(ProductImage::getImagePathUrl).collect(Collectors.toList()).toArray(new String[] {}));
			productInfo.setProductSkuList(productSkuItemService.getProductSkuItemList(id));
			productInfo.setGoodComment(productCommentService.getProductGoodComment(id));

			productInfo.setRecommendList(getProductListByTagName("官方精选", 10));
			productInfo.setHotList(getProductListByTagName("热门商品", 10));
		}
		return productInfo;
	}

	@Override
	public Page<ProductVo> pageProductByCategoryId(Page pageParam, QueryWrapper queryWrapper) {
		return getBaseMapper().pageProductByCategoryId(pageParam, queryWrapper);
	}

	@Override
	public List<ProductVo> getProductListByCategoryId(QueryWrapper queryWrapper) {
		return getBaseMapper().getProductListByCategoryId(queryWrapper);
	}

	@Override
	public List<ProductVo> getProductListByTagName(String tagName, Integer count) {
		return getBaseMapper().getProductListByTagName(tagName, count);
	}

	@Override
	public void updateViewCount(Long id, Long count) {
		getBaseMapper().updateViewCount(id, count);
	}

}
